﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IvashenkoConfigLoader.cs" company="dimamartovoi">
//   Apache License
//   Version 2.0, January 2004
//   http://www.apache.org/licenses
// </copyright>
// <summary>
//   Defines the IvashenkoConfigLoader type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;

using ActorModel.Evolution;
using ActorModel.Infrastructure.Configuration.Ivashenko.Grammar;

using Antlr.Runtime;

namespace ActorModel.Infrastructure.Configuration.Ivashenko
{
    /// <summary>
    /// The ivashenko config loader.
    /// </summary>
    public class IvashenkoConfigLoader : IEngineLoader
    {
        #region Public Methods and Operators

        /// <summary>
        /// The load.
        /// </summary>
        /// <param name="evolutionFunc">
        /// The evolution func.
        /// </param>
        /// <returns>
        /// The <see cref="EngineStartParameters"/>.
        /// </returns>
        public EngineStartParameters<string> Load(string evolutionFunc)
        {
            var interpreter = new Interpreter();
            Func<string, IEnumerable<string>, IEnumerable<string>> handler = interpreter.Interprete(evolutionFunc);
            return this.Load(handler);
        }

        #endregion

        #region Methods

        /// <summary>
        /// The load.
        /// </summary>
        /// <param name="evolutionFunc">
        /// The evolution func.
        /// </param>
        /// <returns>
        /// The <see cref="EngineStartParameters"/>.
        /// </returns>
        private EngineStartParameters<string> Load(Func<string, IEnumerable<string>, IEnumerable<string>> evolutionFunc)
        {
            string simpleConfigPath = Path.Combine(
                Directory.GetCurrentDirectory(), ConfigurationManager.AppSettings["IvashenkoConfig"]);
            var configStream = new ANTLRStringStream(File.ReadAllText(simpleConfigPath));
            var lexer = new IvashenkoConfigLexer(configStream);
            var tokenStream = new CommonTokenStream(lexer);
            var parser = new IvashenkoConfigParser(tokenStream);
            EngineStartParameters<string> parameters = parser.configuration();
            parameters.EvolutionFunc = evolutionFunc;
            return parameters;
        }

        #endregion
    }
}